﻿Ext.define('Html5App.controller.OrderController', {
	extend : 'Ext.app.Controller',
	config : {
		models : [],
		views : [],
		refs : {
			orderList : 'orderList',
			confirmOrderList : 'confirmOrderList',
			sendOrderBySalesCode : 'button[action=sendOrderBySalesCode]',
			confirmOrderBySalesCode : 'button[action=confirmOrderBySalesCode]'
		},
		control : {
			orderList : {
				activate : function(newActiveItem, t, oldActiveItem, eOpts) {
					config.database.transaction(
				        function (tx) {
				        	tx.executeSql("select * from OrderHead where isSend<2 and SalesCode='"+config.current_user.user_name+"' order by OrderNo", [],
				                function (tx, result) {
				                	var htmlStr = '';
                        			Ext.getCmp("order-list-data").setHtml(htmlStr);
                        			if(Number(result.rows.length) > 0){
                        				htmlStr += '<table width="100%" border="0" cellpadding="0" cellspacing="0" style="margin-top:-1px;border-top:1px solid #CFCFCF;border-bottom:1px solid #CFCFCF;font-size:0.7rem;color:#4C4C4C;">';
	                        			for(var i=0;i<result.rows.length;i++){
	                        				var orderObj = result.rows.item(i);
	                        				if(i%2==0){
									  			htmlStr += '<tr style="height:2rem;background-color:#F5F5F5;" onclick="javascript:custom.orderInfoToView(\''+orderObj['OrderNo']+'\');">';
									  		}else{
									  			htmlStr += '<tr style="height:2rem;background-color:#FFFFFF;" onclick="javascript:custom.orderInfoToView(\''+orderObj['OrderNo']+'\');">';
									  		}
	                        				htmlStr += ''+
				                        				'<td style="border-right:1px solid #CFCFCF;text-align:center;width:12%;">'+orderObj['OrderNo']+'</td>'+
													    '<td style="border-right:1px solid #CFCFCF;width:16%;padding-left:0.1rem;">'+orderObj['CustomerCode']+'</td>'+
													    '<td style="border-right:1px solid #CFCFCF;width:30%;padding-left:0.1rem;">'+orderObj['CustomerName']+'</td>'+
													    '<td style="border-right:1px solid #CFCFCF;width:8%;padding-right:0.2rem;text-align:right;">'+orderObj['DetailCount']+'</td>'+
													    '<td style="border-right:1px solid #CFCFCF;width:16%;padding-right:0.2rem;text-align:right;">$'+custom.thousandBitSeparator(orderObj['TotalAmount'],0)+'</td>'+
													    '<td style="width:18%;padding-left:0.1rem;">'+orderObj['DeliveryDate'].replace(/\-/g, "")+'</td>'+
													  '</tr>';
	                        			}
	                        			htmlStr += '</table>';
                        			}
                        			Ext.getCmp("order-list-data").setHtml(htmlStr);
				                },
				                function (tx, error){
				                	
				                }
				            );
				        }
				    );
				}
			},
			confirmOrderList : {
				activate : function(newActiveItem, t, oldActiveItem, eOpts) {
					var now = new Date();
					var curDate = '';
					var curMonth = parseInt(now.getMonth()+1);
				    curDate += now.getFullYear();
				    curDate += '';
					curDate += curMonth < 10 ? '0'+curMonth : curMonth;
					curDate += '';
					curDate += now.getDate() < 10 ? '0'+now.getDate() : now.getDate();
					config.database.transaction(
							function (tx) {
								tx.executeSql("select * from OrderHead where isSend=2 and confirmDate='"+curDate+"' and SalesCode='"+config.current_user.user_name+"' order by OrderNo", [],
										function (tx, result) {
									var htmlStr = '';
									Ext.getCmp("confirm-order-list-data").setHtml(htmlStr);
									if(Number(result.rows.length) > 0){
										htmlStr += '<table width="100%" border="0" cellpadding="0" cellspacing="0" style="margin-top:-1px;border-top:1px solid #CFCFCF;border-bottom:1px solid #CFCFCF;font-size:0.7rem;color:#4C4C4C;">';
										for(var i=0;i<result.rows.length;i++){
											var orderObj = result.rows.item(i);
											if(i%2==0){
												htmlStr += '<tr style="height:2rem;background-color:#F5F5F5;" onclick="javascript:custom.orderInfoToView(\''+orderObj['OrderNo']+'\');">';
											}else{
												htmlStr += '<tr style="height:2rem;background-color:#FFFFFF;" onclick="javascript:custom.orderInfoToView(\''+orderObj['OrderNo']+'\');">';
											}
											htmlStr += ''+
											'<td style="border-right:1px solid #CFCFCF;text-align:center;width:12%;">'+orderObj['OrderNo']+'</td>'+
											'<td style="border-right:1px solid #CFCFCF;width:16%;padding-left:0.1rem;">'+orderObj['CustomerCode']+'</td>'+
											'<td style="border-right:1px solid #CFCFCF;width:30%;padding-left:0.1rem;">'+orderObj['CustomerName']+'</td>'+
											'<td style="border-right:1px solid #CFCFCF;width:8%;padding-right:0.2rem;text-align:right;">'+orderObj['DetailCount']+'</td>'+
											'<td style="border-right:1px solid #CFCFCF;width:16%;padding-right:0.2rem;text-align:right;">$'+custom.thousandBitSeparator(orderObj['TotalAmount'],0)+'</td>'+
											'<td style="width:18%;padding-left:0.1rem;">'+orderObj['DeliveryDate'].replace(/\-/g, "")+'</td>'+
											'</tr>';
										}
										htmlStr += '</table>';
									}
									Ext.getCmp("confirm-order-list-data").setHtml(htmlStr);
								},
								function (tx, error){
									
								}
								);
							}
					);
				}
			},
			sendOrderBySalesCode : {
				tap : function(button, e, eOpts) {
					config.database.transaction(
				        function (tx) {
				        	tx.executeSql("select * from OrderHead where isSend=0 and SalesCode='"+config.current_user.user_name+"' order by OrderNo", [],
				                function (tx, result) {
                        			if(Number(result.rows.length) > 0){
                        				navigator.notification.confirm(
											'確定要傳送列印嗎？',
											function(btnId){
												if(btnId==2){
													var OrderHead = '';
				                        			for(var i=0;i<result.rows.length;i++){
				                        				var orderObj = result.rows.item(i);
				                        				OrderHead += "###"+
				                        				orderObj['OrderNo']+"~~~"+
				                        				orderObj['SalesCode']+"~~~"+
				                        				orderObj['OrderDate']+"~~~"+
				                        				orderObj['DeliveryDate']+"~~~"+
				                        				orderObj['CustomerCode']+"~~~"+
				                        				orderObj['Address']+"~~~"+
				                        				orderObj['Payment']+"~~~"+
				                        				orderObj['TotalAmount']+"~~~"+
				                        				orderObj['NetAmount']+"~~~"+
				                        				orderObj['TotalQty']+"~~~"+
				                        				orderObj['DetailCount']+"~~~"+
				                        				orderObj['CreateTime'];
				                        			}
				                        			config.database.transaction(
												        function (tx) {
												        	tx.executeSql("select * from OrderDetail where isSend=0 and SalesCode='"+config.current_user.user_name+"'",[],
									            				function (tx, resultDetail) {
									            					var OrderDetail = "";
									            					for(var j=0;j<resultDetail.rows.length;j++){
									            						var resultDetailObj = resultDetail.rows.item(j);
									            						OrderDetail += "###"+
									            						resultDetailObj['OrderNo']+"~~~"+
									            						resultDetailObj['DetailNo']+"~~~"+
									            						resultDetailObj['SalesCode']+"~~~"+
									            						resultDetailObj['ItemCode']+"~~~"+
									            						resultDetailObj['OrderQty']+"~~~"+
									            						resultDetailObj['Price']+"~~~"+
									            						resultDetailObj['SubTotal'];
									            					}
									            					util.showLoadMask(null);
												                	Ext.data.JsonP.request({
												                        url: config.global_url+'/sendOrderBySalesCode.html',
												                        callbackKey: 'callback',
												                        params: {
												                        	SalesCode : config.current_user.user_name,
												                        	OrderHead : OrderHead.substr(3),
												                        	OrderDetail : OrderDetail.substr(3)
												                        },
												                        success: function(result, request) {
												                        	if (result.result) {
												                        		util.hideLoadMask();
												                        		util.showMessageMask('列印傳送成功','success-max');
												                        		config.database.transaction(
									        										function (tx) {
														                        		tx.executeSql("update OrderHead set isSend=1 where isSend=0 and SalesCode='"+config.current_user.user_name+"'", [],
																		                    function (tx, result) {},
																		                    function (tx, error) {}
																		                );
																			            tx.executeSql("update OrderDetail set isSend=1 where isSend=0 and SalesCode='"+config.current_user.user_name+"'", [],
																		                    function (tx, result) {},
																		                    function (tx, error) {}
																		                );
									        										}
									        									);
												                        	}else{
												                        		util.hideLoadMask();
												                        		util.showMessageMask(result.msg,'warn-max');
												                        	}
												                        },
												                        failure: function () {
												                        	util.hideLoadMask();
												                        	util.showMessageMask('連接服務器失敗，請稍後再試','error-max');
												                        }
												                    });
												                    
									            				},function (tx, error) {
									            				
									            				}
									            			);
												        }
												    );
												}
											}, '溫馨提示', ['取消','確定']
										);
                        			}else{
                        				util.showMessageMask('沒有訂單可列印傳送','warn-max');
                        			}
				                },
				                function (tx, error){
				                	
				                }
				            );
				        }
				    );
				}
			},
			confirmOrderBySalesCode : {
				tap : function(button, e, eOpts) {
					config.database.transaction(
				        function (tx) {
				        	tx.executeSql("select * from OrderHead where isSend=1 and SalesCode='"+config.current_user.user_name+"' order by OrderNo", [],
				                function (tx, result) {
                        			if(Number(result.rows.length) > 0){
                        				navigator.notification.confirm(
											'確定要確認訂單嗎？',
											function(btnId){
												if(btnId==2){
													util.showLoadMask(null);
								                	Ext.data.JsonP.request({
								                        url: config.global_url+'/confirmOrderBySalesCode.html',
								                        callbackKey: 'callback',
								                        params: {
								                        	SalesCode : config.current_user.user_name
								                        },
								                        success: function(result, request) {
								                        	if (result.result) {
								                        		util.hideLoadMask();
								                        		util.showMessageMask('確認訂單成功','success-max');
								                        		var now = new Date();
								            					var curDate = '';
								            					var curMonth = parseInt(now.getMonth()+1);
								            				    curDate += now.getFullYear();
								            				    curDate += '';
								            					curDate += curMonth < 10 ? '0'+curMonth : curMonth;
								            					curDate += '';
								            					curDate += now.getDate() < 10 ? '0'+now.getDate() : now.getDate();
								                        		config.database.transaction(
					        										function (tx) {
										                        		tx.executeSql("update OrderHead set isSend=2,confirmDate='"+curDate+"' where isSend=1 and SalesCode='"+config.current_user.user_name+"'", [],
														                    function (tx, result) {},
														                    function (tx, error) {}
														                );
															            tx.executeSql("update OrderDetail set isSend=2,confirmDate='"+curDate+"' where isSend=1 and SalesCode='"+config.current_user.user_name+"'", [],
														                    function (tx, result) {},
														                    function (tx, error) {}
														                );
					        										}
					        									);
														        Ext.getCmp("orderHome").removeAll();
																Ext.getCmp("orderHome").add({
																	xtype : 'orderList'
																});
								                        	}else{
								                        		util.hideLoadMask();
								                        		util.showMessageMask(result.msg,'warn-max');
								                        	}
								                        },
								                        failure: function () {
								                        	util.showMessageMask('連接服務器失敗，請稍後再試','error-max');
								                        }
								                    });
												}
									        }, '溫馨提示', ['取消','確定']
										);
                        			}else{
                        				util.showMessageMask('沒有訂單可確認','warn-max');
                        			}
				                },
				                function (tx, error){
				                	
				                }
				            );
				        }
				    );
				}
			}
		}
	}
});